import { systemApi } from '/@/api/sys/system-api'
export const dicMap: Map<string, Map<string, any>> = new Map<string, Map<string, any>>()
export const dicObiect: Map<string, any> = new Map<string, any>()

/**
 * 取数据字典
 */
 export const getDataDictionaryList = (that: any, newArr: Array<string>) => {
	Promise.all(newArr.map(code => setPromise(code))).then((values) => values.forEach((value, i) => {
		that[newArr[i]] = value
		// that.$set(that.dataDictionaryList, newArr[i], value)
	}))
}

export const setPromise = (codes: string) => {
	return new Promise((resolve) => {
		getDicMap(codes, (res: any) => {
			resolve(res)
		})
	})
}

/**
 * 返回数据字典
 * @param code 字典编码
 * @param fun 回调方法
 * @returns {Promise<void>}
 */
 export async function getDicMap(code: string, fun: Function) {
	if (dicMap.get(code) === undefined) {
		getDicText(code, function (data: any) {
			if ((typeof data === 'object') && data.constructor === Array) {
				const obj: Map<string, any> = new Map<string, any>()
				data.forEach(function (item) {
					if (item.dataCode !== '!') {
						obj.set(item.dataCode, item.dataName)
					}
				})
				dicMap.set(code, obj)
				fun(obj)
			}
		})
	} else {
		fun(dicMap.get(code))
	}
}

/**
 * 数得数据字典文本
 * @param code
 */
 export function getDicText(classCode: string, fun: Function) {
	systemApi.getDicListByCode(classCode).then((data) => {
    fun(data.data)
  })
}

/**
 * 返回数据字典(排序用)
 * @param code 字典编码
 * @param fun 回调方法
 * @returns {Promise<void>}
 */
 export async function getDicObject(code: string, fun: Function) {
  if (dicObiect.get(code) === undefined) {
    getDicText(code, function (data: any) {
      if (typeof data === 'object' && data.constructor === Array) {
        const arr: { key: string; value: string }[] = []
        data.forEach(function (item) {
          if (item.dataCode !== '!') {
            const obj = {
              key: '',
              value: '',
            }
            obj.key = item.dataCode
            obj.value = item.dataName
            arr.push(obj)
          }
        })
        dicObiect.set(code, arr)
        fun(arr)
      }
    })
  } else {
    fun(dicObiect.get(code))
  }
}